<?php

/**
 * article actions.
 *
 * @package    jiazhang
 * @subpackage article
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class articleActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
        $dql = Doctrine::getTable('Article')->createQuery()->orderBy('created_at desc');
        $page = $request->getParameter('page',1);
        $this->pager = new sfDoctrinePager('Article',30);
        $this->pager->setQuery($dql);
        $this->pager->setPage($page);
        $this->pager->init();
  }
  
  public function executeAdd(sfWebRequest $request)
  {
   
  }
  
  public function executeDel(sfWebRequest $request)
  {
      $this->forward404Unless($article = Doctrine::getTable('Article')->findOneById($id = $request->getParameter('id',0)));
      $article->delete();
      Doctrine::getTable('RecommendArticle')->createQuery()->where('article_id = ?',$id)->delete()->execute();
      Doctrine::getTable('ArticleTag')->createQuery()->where('article_id = ?',$id)->delete()->execute();
      Doctrine::getTable('ArticleAttribute')->createQuery()->where('article_id = ?',$id)->delete()->execute();
      Doctrine::getTable('ArticleComment')->createQuery()->where('article_id = ?',$id)->delete()->execute();
      $this->getUser()->setFlash('success', '删除成功！');
      $this->redirect('article/index');
  }
  
  public function executeRecommend(sfWebRequest $request){
      $position = (int)$request->getParameter('position',0);
      $this->position_info = array();
      $positions = Doctrine::getTable('RecommendArticle')->findAll();
      
      foreach($positions as $position_obj){
          $this->position_info[$position_obj->getPosition()] = array(
              'cover'=>$position_obj->getCover(),
              'title'=>$position_obj->getTitle()
          );
      }
      
      if($position != 0){
          $this->recommend_article = Doctrine::getTable('RecommendArticle')->findOneBy('position',$position);
      }
      
      if($request->isMethod('POST')){
          
          $title = trim($request->getParameter('title',''));
          $post_article_id = (int)$request->getParameter('article_id',0);
          $cover = $request->getFiles('cover');
          $pre_cover_url = $request->getParameter('image_url');
          
          if($cover['error'] == 0){
              
            $file_name = $cover['name'];
            $file_ext_tmp = explode('.', $file_name);
            $file_ext = $file_ext_tmp[count($file_ext_tmp)-1];
            $allow_file_type = array('jpg','bmp','png','gif','jpeg');
              
            if(in_array($file_ext, $allow_file_type)){
                $year = date('Y',time());
                $month = date('m',time());
                $day = date('d',time());
                $save_file_name = $year.'_'.$month.'_'.$day.'_'.substr(md5(time()+rand(0,999)),25).'.'.$file_ext;
                $upyun_save_path = '/article_cover/'.$year.'/'.$month.'/'.$day.'/'.$save_file_name;
                $upyun = new UpYun('onetongxue', 'onetongxue', 'onetongxue2015');
                $image_url=  '';
                
                try {
                    $fh = fopen($cover['tmp_name'], 'rb');
                    $rsp = $upyun->writeFile($upyun_save_path, $fh, True);   // 上传图片，自动创建目录
                    $image_url=  sfConfig::get('app_img_url').$upyun_save_path;
                    fclose($fh);
                }
                catch(Exception $e) {
                    echo $e->getCode();
                    echo $e->getMessage();
                }
            }else{
                $this->getUser()->setFlash('error', '封面类型错误！');
                $this->redirect('article/recommend');
            }
          
         }else{
             $image_url = $pre_cover_url;
         }
          
          
          if($this->recommend_article){
              $article_id = $this->recommend_article->getArticleId();
              $article = Doctrine::getTable('Article')->findOneById($article_id);
              $article->setIsCommend(0)->save();
          }
          Doctrine::getTable('RecommendArticle')->createQuery()->where('position = ?',$position)->delete()->execute();
//          $article_id = ($this->recommend_article) ? $this->recommend_article->getArticleId() : $post_article_id;
          $recommend_article = new RecommendArticle();
          $recommend_article->setTitle($title)->setArticleId($post_article_id)->setCover($image_url)->setPosition($position)->save();
          $this->getUser()->setFlash('success', '成功编辑推荐位！');
          $this->redirect('article/recommend');
      }
      
  }
  
  public function executeEdit(sfWebRequest $request)
  {
      $this->forward404Unless($this->article = Doctrine::getTable('Article')->findOneById($id = (int)$request->getParameter('id')));
      
      if($request->isMethod('POST')){
          
          $title = trim($request->getParameter('title',''));
          $display = (int)$request->getParameter('display',1);
          $author = (int)($request->getParameter('author',''));
          $cover = $request->getFiles('cover');
          $summary = $request->getParameter('summary','');
          $content = $request->getParameter('content','');
          $tags = trim($request->getParameter('tags',''));
          $phone_content = trim($request->getParameter('phone_content',''));
          $change_author = 0;
          $article = $this->article;
          
          if($this->article->getAuthor() != $author){
              $this->article->getAuthorObj()->decreaseArticleNum();
              $change_author=1;
          }
          
          Doctrine::getTable('ArticleTag')->createQuery()->where('article_id = ?',$id)->execute()->delete();
          $article->setTitle($title)->setDisplay($display)->setAuthor($author)->setPhoneContent($phone_content)->setSummary($summary)->setContent($content)->setTags($tags)->save();
          $article->getArticleAttr()->setDisplay($display)->save();
          
          if($change_author){
              $author = Doctrine::getTable('ArticleAuthor')->findOneById($author);
              $author->addArticleNum();
          }
          
          $article_id = $id;
          
          if(strlen($tags) >= 1){
              $tags = explode(',', $tags);
              foreach($tags as $tag){
                  if(strlen(trim($tag)) == 0) continue;
                  $tag_obj = new ArticleTag();
                  $tag_obj->setArticleId($article_id)->setTag($tag)->save();
              }
          }
          
          if($cover['error'] == 0){
              
            $file_name = $cover['name'];
            $file_ext_tmp = explode('.', $file_name);
            $file_ext = $file_ext_tmp[count($file_ext_tmp)-1];
            $allow_file_type = array('jpg','bmp','png','gif','jpeg');
              
            if(in_array($file_ext, $allow_file_type)){
                $year = date('Y',time());
                $month = date('m',time());
                $day = date('d',time());
                $save_file_name = $year.'_'.$month.'_'.$day.'_'.substr(md5(time()+rand(0,999)),25).'.'.$file_ext;
                $upyun_save_path = '/article_cover/'.$year.'/'.$month.'/'.$day.'/'.$save_file_name;
                $upyun = new UpYun('onetongxue', 'onetongxue', 'onetongxue2015');
                $image_url=  '';
                
                try {
                    $fh = fopen($cover['tmp_name'], 'rb');
                    $rsp = $upyun->writeFile($upyun_save_path, $fh, True);   // 上传图片，自动创建目录
                    $image_url=  sfConfig::get('app_img_url').$upyun_save_path;
                    fclose($fh);
                }
                catch(Exception $e) {
                    echo $e->getCode();
                    echo $e->getMessage();
                }
            }else{
                $this->getUser()->setFlash('error', '封面类型错误！');
                $this->redirect('article/edit');
            }
            
          }
          
          if(strlen($image_url) > 0 ){
              $article->setCover($image_url)->save();
          }
          
        $this->getUser()->setFlash('success', '文章编辑成功！');
        $this->redirect('article/index');
      }
  }
  
  public function executeCreate(sfWebRequest $request){
      if($request->isMethod('POST')){
          
          $title = trim($request->getParameter('title',''));
          $display = (int)$request->getParameter('display',1);
          $author = (int)($request->getParameter('author',''));
          $cover = $request->getFiles('cover');
          $summary = $request->getParameter('summary','');
          $content = $request->getParameter('content','');
          $tags = trim($request->getParameter('tags',''));
          $phone_content = $request->getParameter('phone_content','');
          
          if($author == 0){
                $this->getUser()->setFlash('error', '请先添加文章作者！');
                $this->redirect('article/add');
          }
          
          $article = new Article();
          $article->setTitle($title)->setDisplay($display)->setAuthor($author)->setPhoneContent($phone_content)->setCover('')->setSummary($summary)->setContent($content)->setTags($tags)->trySave();
          $article->getAuthorObj()->addArticleNum();
          $article_id = $article->getId();

          if(strlen($tags) >= 1){
              $tags = explode(',', $tags);
              foreach($tags as $tag){
                  if(strlen(trim($tag)) == 0) continue;
                  $tag_obj = new ArticleTag();
                  $tag_obj->setArticleId($article_id)->setTag($tag)->save();
              }
          }
          
          if($cover['error'] == 0){
              
            $file_name = $cover['name'];
            $file_ext_tmp = explode('.', $file_name);
            $file_ext = $file_ext_tmp[count($file_ext_tmp)-1];
            $allow_file_type = array('jpg','bmp','png','gif','jpeg');
              
            if(in_array($file_ext, $allow_file_type)){
                $year = date('Y',time());
                $month = date('m',time());
                $day = date('d',time());
                $save_file_name = $year.'_'.$month.'_'.$day.'_'.substr(md5(time()+rand(0,999)),25).'.'.$file_ext;
                $upyun_save_path = '/article_cover/'.$year.'/'.$month.'/'.$day.'/'.$save_file_name;
                $upyun = new UpYun(sfConfig::get('app_upyun_space'),sfConfig::get('app_upyun_user') , sfConfig::get('app_upyun_pwd'));
                $image_url=  '';
                
                try {
                    $fh = fopen($cover['tmp_name'], 'rb');
                    $rsp = $upyun->writeFile($upyun_save_path, $fh, True);   // 上传图片，自动创建目录
                    $image_url=  sfConfig::get('app_img_url').$upyun_save_path;
                    fclose($fh);
                }
                catch(Exception $e) {
                    echo $e->getCode();
                    echo $e->getMessage();
                }
            }else{
                $this->getUser()->setFlash('error', '封面类型错误！');
                $this->redirect('article/add');
            }
            
          }
          
          $article->setCover($image_url)->save();
          
        $this->getUser()->setFlash('success', '文章添加成功！');
        $this->redirect('article/index');
      }
  }
  
}
